import { useAuthStore } from '@/store/modules/auth';
import { localStg, sessionStg } from '@/utils/storage';
import { getRefreshToken, getToken } from '@/store/modules/auth/shared';
import { fetchRefreshToken } from '../api';
import type { RequestInstanceState } from './type';

export function getAuthorization() {
  const token = getToken();
  let Authorization = {};
  if (token && token.tokenName && token.tokenValue) {
    Authorization = {
      [token.tokenName]: `Bearer ${token.tokenValue}`
    };
  }

  return Authorization;
}

/** refresh token */
export async function handleRefreshToken() {
  const { resetStore } = useAuthStore();

  const rToken = getRefreshToken() || <Api.Auth.LoginToken>{};
  const refreshTokenMethod = fetchRefreshToken(rToken);

  // set the refreshToken role, so that the request will not be intercepted
  refreshTokenMethod.meta.authRole = 'refreshToken';

  try {
    const data = await refreshTokenMethod;
    if (rToken.rememberMe) {
      localStg.set('token', data);
    } else {
      sessionStg.set('token', data);
    }
  } catch (error) {
    await resetStore();
    throw error;
  }
}

export function showErrorMsg(state: RequestInstanceState, message: string) {
  if (!state.errMsgStack?.length) {
    state.errMsgStack = [];
  }

  const isExist = state.errMsgStack.includes(message);

  if (!isExist) {
    state.errMsgStack.push(message);

    if (window.$message) {
      window.$message({
        type: 'error',
        message,
        onClose: () => {
          state.errMsgStack = state.errMsgStack.filter(msg => msg !== message);

          setTimeout(() => {
            state.errMsgStack = [];
          }, 5000);
        }
      });
    }
  }
}
